package org.example.im.service.impl;

import org.example.im.dto.UserDTO;
import org.example.im.entity.User;
import org.example.im.repository.UserRepository;
import org.example.im.service.UserService;
import org.example.im.websocket.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserRepository userRepository;
    
    @Override
    public User register(String username, String password) {
        if (userRepository.existsByUsername(username)) {
            throw new RuntimeException("用户名已存在");
        }
        
        User user = new User();
        user.setUsername(username);
        user.setPassword(password); // 实际项目中应该对密码进行加密处理
        user.setCreateTime(new Date());
        
        return userRepository.save(user);
    }
    
    @Override
    public User login(String username, String password) {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        if (!user.getPassword().equals(password)) { // 实际项目中应该对密码进行加密后再比较
            throw new RuntimeException("密码错误");
        }
        
        user.setLastLoginTime(new Date());
        user.setOnline(true);
        
        return userRepository.save(user);
    }
    
    @Override
    public List<UserDTO> getAllUsers() {
        return userRepository.findAll().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    @Override
    public User getUserById(Long id) {
        return userRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
    }
    
    @Override
    public User getUserByUsername(String username) {
        return userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
    }
    
    private UserDTO convertToDTO(User user) {
        UserDTO dto = new UserDTO();
        dto.setId(user.getId());
        dto.setUsername(user.getUsername());
        dto.setOnline(WebSocketServer.isUserOnline(user.getId()));
        return dto;
    }
} 